import axios, {
  type AxiosResponse,
  type InternalAxiosRequestConfig
} from 'axios'
import { ElMessage } from 'element-plus'

interface ApiError {
  response?: {
    data?: {
      error?: {
        message?: string
      }
    }
  }
}

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000
})

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers.Authorization = 'Bearer token'

    if (config.method?.toLocaleUpperCase() === 'GET') {
      config.url += `?n=${Date.now()}`
    }
    return config
  },
  (error: Error) => {
    // do something with request error
    if (import.meta.env.MODE === 'development') {
      console.log(error) // for debug
    }
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data

    if (response.status === 200 || response.status === 201) {
      ElMessage({
        type: 'success',
        message: res.message,
        duration: 1500
      })
      return res
    } else {
      ElMessage({
        type: 'error',
        message: res.message,
        duration: 1500
      })
      return Promise.reject(res.message)
    }
  },
  (error: Error) => {
    if (import.meta.env.MODE === 'development') {
      console.log(error) // for debug
    }

    const errorMessage =
      (error as ApiError).response?.data?.error?.message || '请求出错，请重试'

    ElMessage({
      type: 'error',
      message: errorMessage,
      duration: 1500
    })
    return Promise.reject(error)
  }
)

// 添加各种HTTP方法的便捷函数
export const get = <T = any>(url: string, params?: any): Promise<T> => {
  return service.get(url, { params })
}

export const post = <T = any>(url: string, data?: any): Promise<T> => {
  return service.post(url, data)
}

export const put = <T = any>(url: string, data?: any): Promise<T> => {
  return service.put(url, data)
}

export const del = <T = any>(url: string): Promise<T> => {
  return service.delete(url)
}

export const patch = <T = any>(url: string, data?: any): Promise<T> => {
  return service.patch(url, data)
}

export default service
